// 导入uni-fetch
import {createUniFetch} from 'uni-app-fetch'
import { useUserStore } from '@/stores/user'

const userStore = useUserStore()

// tabbar页面列表
const tabbarList = [
  'pages/task/index',
  'pages/message/index',
  'pages/my/index'
]


export const uniFetch = createUniFetch({
  // 设置响应的标识
  loading:{
    title:'正在加载中...'
  },
  // 基地址
  baseURL:'https://slwl-api.itheima.net',
  intercept: {
    // 请求拦截器
    request(options){
      // 合并请求头token,和其他信息
      const defaultHeader = {
        Authorization:userStore.token
      }
      options.header = Object.assign({},defaultHeader,options.header)
      return options
    },
    // 响应拦截器
    response({data,statusCode}){

      // 记录跳转前的页面
      const currentPages = getCurrentPages()
      const redirectUrl = currentPages[currentPages.length-1].route
      const redirectType = tabbarList.includes(redirectUrl)?'switchTab':'redirectTo'
      // 判断未登录时的响应
    if(statusCode === 401) {
        uni.reLaunch({
          url:`/pages/login/index?redirectUrl=/${redirectUrl}&redirectType=${redirectType}`
        })
      }
      return data
    }
  }
})
